package com.saiaweather.android;




import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;


import android.app.ProgressDialog;


import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.saiaweather.android.db.City;
import com.saiaweather.android.db.County;
import com.saiaweather.android.db.Province;
import com.saiaweather.android.db.SaiaWeatherDB;
import com.saiaweather.android.util.HttpUtil;
import com.saiaweather.android.util.Utilty;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ChooseAreaFragment extends Fragment {
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    private Button backButton;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    //？？
    private List<String> datalist = new ArrayList<>();
    private SaiaWeatherDB saiaWeatherDB;

    //省市县列表
    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;

    //被选中的省市，和级别
    private Province selectedProvince;
    private City selectedCity;

    private int currentLevel;

//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//
//            progressDialog.dismiss();
//
//    }
//
//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        progressDialog.dismiss();
//    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area, container, false);
        titleText =  view.findViewById(R.id.title_text);
        backButton =  view.findViewById(R.id.back_button);
        listView =  view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, datalist);
        listView.setAdapter(adapter);
        //实例化db对象
        saiaWeatherDB = SaiaWeatherDB.getInstance(getContext());
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (currentLevel == LEVEL_PROVINCE) {
                    selectedProvince = provinceList.get(position);
                    queryCities();
                }else if (currentLevel==LEVEL_CITY) {
                    selectedCity=cityList.get(position);
                    queryCounty();
                }
            }
        });
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(currentLevel==LEVEL_COUNTY) {
                    queryCities();
                } else if(currentLevel ==LEVEL_CITY) {
                    queryProvinces();
                }
            }
        });
        queryProvinces();
        return view;
    }


    //服务器查找省市县数据，有保存到数据库，再在数据库中查询一遍
    private void queryFromServer(String address, final String type) {
        showProgressDialog();
        Log.d(getTag(),"失败111");
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Log.d(getTag(),"失败222");
                        Toast.makeText(getContext(),"加载失败",Toast.LENGTH_LONG).show();
                    }
                });

            }


            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseText = response.body().string();
                boolean result = false;
                Log.d(getTag(),"失败888");
                if ("province".equals(type)) {
                    result = Utilty.handleProvinceResponse(responseText, getContext());
                } else if ("city".equals(type)) {
                    result = Utilty.handleCityResponse(getContext(), responseText,
                            selectedProvince.getId());
                } else if ("county".equals(type)) {
                    result = Utilty.handleCountyResponse(getContext(), responseText,
                            selectedCity.getId());
                }
                //服务器有结果
                if (result) {
                    //切换到主线程
                    Log.d(getTag(),"失败333");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) {
                                queryProvinces();
                            } else if ("city".equals(type)) {
                                queryCities();
                            } else if ("county".equals(type)) {
                                queryCounty();
                            }
                        }
                    });
                }

            }
        });


    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        Log.d(getTag(),"失败444");
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    //关闭进度对话框
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }


    //查询全国的省，先数据库，再服务器
    private void queryProvinces() {
        titleText.setText("中国");
        Log.d(getTag(),"失败555");
        backButton.setVisibility(View.GONE);
        provinceList = saiaWeatherDB.loadProvince();
        Log.d(getTag(),"失败9999");
        if (provinceList.size() > 0) {
            datalist.clear();
            for (Province province : provinceList) {
                datalist.add(province.getProvinceName());
            }
            //???
            adapter.notifyDataSetChanged();
            //???
            listView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            String address = "http://guolin.tech/api/China";
            //从服务器获取数据保存在数据库，然后再查询一遍
            Log.d(getTag(),"失败666");
            queryFromServer(address, "province");
        }
    }

    //查询全国的市县，先数据库，再服务器
    private void queryCities() {
        titleText.setText(selectedProvince.getProvinceName());
        Log.d(getTag(),"失败777");
        backButton.setVisibility(View.VISIBLE);
        cityList = saiaWeatherDB.loadCity(selectedCity.getId());
        if (cityList.size() > 0) {
            datalist.clear();
            for (City city : cityList) {
                datalist.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_CITY;
        } else {
            String provinceCode = selectedProvince.getProvinceCode();
            String address = "http://guolin.tech/api/China/" + provinceCode;
            queryFromServer(address, "city");
        }

    }

    //查询全国的县，先数据库，再服务器
    private void queryCounty() {
        titleText.setText(selectedCity.getCityName());
        backButton.setVisibility(View.VISIBLE);
        countyList = saiaWeatherDB.loadCounty(selectedCity.getId());
        if (countyList.size() > 0) {
            datalist.clear();
            for (County county  : countyList ) {
                datalist.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            String provinceCode=selectedProvince.getProvinceCode();
            String cityCode=selectedCity.getCityCode();
            String address = "http://guolin.tech/api/China/" + provinceCode+"/"+cityCode;
            queryFromServer(address, "county");
        }


    }









    /*
    @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }
     */
    //被弃用，以下为代替方案

//    @Override
//    public void onAttach(@NonNull Context context) {
//        super.onAttach(context);
//
//        //requireActivity() 返回的是宿主activity
//        requireActivity().getLifecycle().addObserver(new LifecycleEventObserver() {
//            @Override
//            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
//                if (event.getTargetState() == Lifecycle.State.CREATED) {
//                    //to do here
//                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                        @Override
//                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//                            if (currentLevel == LEVEL_PROVINCE) {
//                                selectedProvince = provinceList.get(position);
//                                queryCities();
//                            }else if (currentLevel==LEVEL_CITY) {
//                                selectedCity=cityList.get(position);
//                                queryCounty();
//                            }
//                        }
//                    });
//                    backButton.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            if(currentLevel==LEVEL_COUNTY) {
//                                queryCities();
//                            } else if(currentLevel ==LEVEL_CITY) {
//                                queryProvinces();
//                            }
//                        }
//                    });
//                    queryProvinces();
//                    //记得删除观察者
//                    getLifecycle().removeObserver(this);
//                }
//            }
//        });
//    }


}
